package com.etung.iot.demo.handler;

import com.etung.iot.demo.configs.TopicConfig;
import com.etung.iot.demo.utils.ClassUtil;
import com.etung.iot.demo.utils.SpringContextUtils;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

@Slf4j
public class HandlerFactory {
    private static Map<String,TopicHandler> handlerMaps = Maps.newHashMap();
    public static TopicHandler getTopicHandler(String topic){
        return handlerMaps.getOrDefault(getGeneralTopic(topic), SpringContextUtils.getBean(DefaultTopicHandler.class));
    }

    public static void registerHandler(String key,TopicHandler handler){
        handlerMaps.put(key,handler);
    }

    private static String getGeneralTopic(String topic){
        if (topic.startsWith(TopicConfig.SYS_TOPIC_PREFIX)) return TopicConfig.SYS_TOPIC;
        int idx = topic.lastIndexOf("/");
        if(idx != -1){
            String suffix = topic.substring(idx);
            for(String key: handlerMaps.keySet()){
                if(key.endsWith(suffix)){
                    return key;
                }
            }
        }
        return topic;
    }
}
